package leetcode;

 interface MountainArray {
     public int get(int index);

     public int length();
 }

public class Leetcode1095 {
    public int findInMountainArray(int target, MountainArray mountainArr) {
        int len = mountainArr.length();
        int peakIndex = getPeakIndex(mountainArr,0,len-1);//peakIndex
        int index1 = getindexl(mountainArr,0,peakIndex,target);//index1
        int index2 = getindex2(mountainArr,peakIndex,len-1,target);//index2
        return (index1==-1)?index2:index1;
    }
    //getPeakIndex
    public int getPeakIndex(MountainArray mountainArr,int left,int right){
        while(left<right){
            int mid = left + (right-left)/2;
            //[mid+1,right]
            if(mountainArr.get(mid)<mountainArr.get(mid+1)){
                left = mid+1;
                //[left,mid]
            }else{
                right = mid;
            }
        }
        //left==right
        return left;
    }
    //getindexl
    public int getindexl(MountainArray mountainArr,int left,int right,int target){
        while(left<right){
            int mid = left + (right-left)/2;
            //[mid+1,right]
            if(mountainArr.get(mid)<target){
                left = mid+1;
                //[left,mid]
            }else{
                right = mid;
            }
        }
        //left==right
        if(mountainArr.get(left)==target){
            return left;
        }
        return -1;
    }
    //getIndex2
    public int getindex2(MountainArray mountainArr,int left,int right,int target){
        while(left<right){
            int mid = left + (right-left+1)/2;
            //[left,mid-1]
            if(mountainArr.get(mid)<target){
                right = mid - 1;
                //[mid,right]
            }else{
                left = mid;
            }
        }
        //left==right
        if(mountainArr.get(left)==target){
            return left;
        }
        return -1;
    }
}
